package org.easystub;

public class Capture {

    private Invocation capturedInvocation;

    public void handleInvocation(Invocation invocation) {
        capturedInvocation = invocation;
    }

    @SuppressWarnings("unchecked")
    public <T> T getValue() {
        return (T) getValueAtPosition(0);
    }

    @SuppressWarnings("unchecked")
    public <T> T getValueAtPosition(int position) {
        checkInvocationRegistered();

        Object[] methodArguments = capturedInvocation.getMethodArguments();
        try {
            return (T) methodArguments[position];
        } catch (ArrayIndexOutOfBoundsException e) {
            String message = String.format("The invocation captured only has %s argument(s). " +
                    "You asked for argument %s",
                    methodArguments.length, position + 1);
            throw new IllegalArgumentException(message);
        }
    }

    private void checkInvocationRegistered() {
        if(capturedInvocation == null) {
            throw new IllegalStateException("No invocations have been captured");
        }
    }
}
